class BookController < ApplicationController
  
  #This is currently the home page, and the browse book method.  It will eventually only do one.
  def index
    @all_books = Book.getAllBooks
    @popular_books = Book.getAllBooks
    @index_books = Book.find(:all, :conditions => ['ucase(left(title,1)) = ?',params[:letter] ], :order => 'title')
    #for the search
     @search = params[:search]
   @books = Book.search(@search)
  end
  
  #a view for finding books by their title.
 

    #shows the details of a book
  def show
    @book = Book.find(params[:id])
    @condition = Condition.find(@book.condition_id)
    @user = User.find(@book.user_id)
    @tag_list = @book.tag_list
    @tags = @book.tag_counts
  end
  
  #this method will now use the signed in user to add a book.  No longer can you add a book without joining textbook trader.
  #If you are not logged in, it will direct you to log in.
  def new
    if logged_in?
      @user = User.find(session[:user]) 
      @conditions = Condition.find(:all)
    else
      redirect_to :controller => "user", :action => "login"
    end 
  end
  
  #compliment of new.  New was the view, create is the action that adds the book to the DB
  #We get the userID from the session now instead of the list.
  def create
    @user = User.find(session[:user]) 
    @book = Book.new(params[:book])
    @book.user_id = session[:user]
    setup_tags @book
    if @book.save
      flash[:notice] = 'Your book is ready to be traded'
      redirect_to :controller=> "user", :action => "mybooks"
    else
      render :action => "new"
    end
  end

  #for security, we make sure the user is logged in, and the current user owns the book
  def edit
    if logged_in?
      @user = User.find(session[:user]) 
      @book = Book.find(params[:id])
      @tag_list = @book.tag_list
    else
      redirect_to :controller => "user", :action => "login"
    end
    #Security, make sure the user is the owner of the book before we allow them to edit it.
    if session[:user] != @book.user_id
      flash[:notice] = 'Please do not try to edit other users books'
      redirect_to :action => "index"
    end
  end

  
  def update
    @book = Book.find(params[:id])
    setup_tags @book
    if @book.update_attributes(params[:book])
      flash[:notice] = 'Updated'
      redirect_to :action => "index"
    else
      render :action => "edit"
    end
  end

    #not implemented yet
  def destroy
  end

  def search
   @search = params[:search]
   @books = Book.search(@search)
  end
  
  #there is the option to see books by their tag.  This view does that for us.
  def tag
    @books = Book.find_tagged_with(params[:id], :match_all => true)
  end
  
  private  
  def setup_tags(book)
    unless params[:tag_list].blank?
      @book.tag_list = params[:tag_list].split(",")
    end
  end
    
  
end
